'use client';

import React, { useImperativeHandle, useState } from 'react';
import clsx from 'clsx';
import toast from 'react-hot-toast';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useForm } from 'react-hook-form';

export interface Values {
  name: string;
  description?: string;
}

export interface FormFolderProps {
  className?: string;
  ref?: React.Ref<ReturnType<typeof useForm<Values>>>;
  defaultValues?: Partial<Values>;
  onSubmit?: (data: Values) => void | Promise<void>;
}

const formSchema = z.object({
  name: z
    .string({
      required_error: '文件夹名称为必填项',
    })
    .min(1, {
      message: '文件夹名称不能为空',
    })
    .max(50, {
      message: '文件夹名称不能超过 50 个字符',
    }),
  description: z
    .string()
    .max(250, {
      message: '描述不能超过 250 个字符',
    })
    .optional(),
});

function FormFolderNoMemoized(props: FormFolderProps) {
  const { ref, className, defaultValues, onSubmit } = props;

  const [loading, setLoading] = useState(false);

  const form = useForm<Values>({
    defaultValues,
    resolver: zodResolver(formSchema),
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = form;

  useImperativeHandle(ref, () => form, [form]);

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        const submit = handleSubmit((data) => {
          try {
            if (onSubmit) {
              setLoading(true);
              const cb = onSubmit(data);
              if (cb instanceof Promise) {
                cb.then(() => {
                  setLoading(false);
                }).catch((error) => {
                  setLoading(false);
                  toast.error((error as Error)?.message || '提交失败，请稍后重试');
                });
                return;
              }
              setLoading(false);
            }
          } catch (error) {
            setLoading(false);
            toast.error((error as Error)?.message || '提交失败，请稍后重试');
          }
        });
        submit(e);
      }}
    >
      <fieldset className={clsx('fieldset', className)}>
        <label className="label required-mark">文件夹名称</label>
        <input
          {...register('name')}
          type="text"
          className="w-full input"
          placeholder="请填写文件夹名称"
        />
        <p className="h-3 text-xs text-error">{errors.name?.message}</p>

        <label className="label">描述</label>
        <textarea
          {...register('description')}
          className="w-full textarea"
          placeholder="请填写文件夹描述"
        />
        <p className="h-3 text-xs text-error">{errors.description?.message}</p>

        <label className="label">注意：该文件夹在当前目录下创建，请注意您当前的文件夹路径。</label>

        <button type="submit" className="btn btn-primary mt-4" disabled={loading}>
          {loading && <span className="loading loading-spinner" />}
          {loading ? '提交中' : '提交'}
        </button>
      </fieldset>
    </form>
  );
}

export const FormFolder = React.memo(FormFolderNoMemoized);
